/*  This file is a part of JJSched source code
    JJSched - Java Jabber Scheduler - a simple Jabber scheduling application
    Copyright (C) 2008 Cestmir "CZestmyr" Houska

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/> */

package czestmyr.jjsched;

import java.util.*;

/**
 * Serves for holding definitions of all defined global macros.
 * A macro is a substitution rule for simplifying the jjsched command 
 * syntax. A macro has its keyword and body. When the substitution takes
 * place, each occurence of the keyword token is replaced by the list
 * of tokens in the body. The substitution is non-recursive - e.g. the
 * macro body cannot contain keywords of other macros.
 */
public class Macros{
    /**
     * Default constructor
     */
    Macros(){
        macro_table = new HashMap<String, Vector<String>>();
    }

    /**
     * Determines whether a token is a macro keyword.
     *
     * @param	token	the token in question
     * @return		true if the token is a keyword of a macro, false otherwise
     */
    boolean isMacro(String token){
        if (macro_table.containsKey(token)) return true;
        else return false;
    }

    /**
     * Returns body of macro with the keyword token.
     *
     * @param	token	the keyword token
     * @return		body of macro with the keyword token if the macro is defined,
     *			null otherwise
     */
    Vector<String> getMacroBody(String token){
        Vector<String> ret;
        try {
            ret = macro_table.get(token);
        } catch (Exception e) {
            ret = null;
        }
        return ret;
    }

    /**
     * Creates a new macro with the specified keyword and body.
     * Replaces the macro if it already exists with the given keyword.
     *
     * @param	keyword	keyword of the new macro
     * @param	body	iterator on the list containing body of the new macro
     */
    void newMacro(String keyword, Iterator<String> body){
        Vector<String> macro = new Vector<String>();

        while (body.hasNext()){
            macro.add(body.next());
        }

        macro_table.put(keyword, macro);
    }

    /**
     * Returns an iterator to the macro table
     */
    Iterator getMacrosIterator(){
        return macro_table.entrySet().iterator();
    }

    /**
     * The data structure used to hold global macro definitions.
     */
    HashMap<String, Vector<String>> macro_table;
}